using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

/// <summary>
/// 【对象池管理器】
/// 适用场景：用于频繁生成/销毁的物体（如子弹、特效、敌人等）
/// 功能：
/// - 支持按名称分类复用对象
/// - 自动创建容器管理回收对象
/// - 支持对象回收和重用
/// </summary>
public class ObjectPoolManager : MonoBehaviour
{
    /// <summary>静态对象池列表，每类物体一个池</summary>
    public static List<PooledObjectInfo> ObjectPools = new List<PooledObjectInfo>();

    /// <summary>
    /// 生成对象：从池中复用或新建
    /// </summary>
    /// <param name="objectToSpawn">要生成的预制体</param>
    /// <param name="spawnPosition">生成位置</param>
    /// <param name="spawnRotation">生成旋转</param>
    /// <returns>返回激活的对象</returns>
    public static GameObject SpawnObject(GameObject objectToSpawn, Vector3 spawnPosition, Quaternion spawnRotation)
    {
        string lookupKey = objectToSpawn.name;

        // 查找或新建对象池
        PooledObjectInfo pool = ObjectPools.Find(p => p.LookupString == lookupKey);

        //PooledObjectInfo pool = null;
        //foreach (PooledObjectInfo p in ObjectPools)
        //{
        //    if(p.LookupString==objectToSpawn.name)
        //    {
        //        pool = p;
        //        break;
        //    }
        //}

        if (pool == null)
        {
            pool = new PooledObjectInfo()
            {
                LookupString = lookupKey,
                container = new GameObject(lookupKey + "_Pool")
            };
            ObjectPools.Add(pool);
        }

        // 尝试从池中取出未激活对象
        GameObject spawnableObj = pool.InactiveObjects.FirstOrDefault();

        //GameObject spawnableObj = null;
        //foreach (GameObject obj in pool.InactiveObjects)
        //{
        //    if (obj != null)
        //    {
        //        spawnableObj = obj;
        //        break;
        //    }
        //}

        if (spawnableObj == null)
        {
            // 无可用对象，实例化新对象
            spawnableObj = Instantiate(objectToSpawn, spawnPosition, spawnRotation);
            spawnableObj.name = lookupKey; // 保持名称一致，方便回收
            spawnableObj.transform.SetParent(pool.container.transform);
        }
        else
        {
            // 从池中激活复用对象
            spawnableObj.transform.position = spawnPosition;
            spawnableObj.transform.rotation = spawnRotation;
            pool.InactiveObjects.Remove(spawnableObj);
            spawnableObj.SetActive(true);
        }

        return spawnableObj;
    }

    /// <summary>
    /// 回收对象：将对象放入池中待复用
    /// </summary>
    /// <param name="obj">要回收的对象</param>
    public static void ReturnObjectToPool(GameObject obj)
    {
        string key = obj.name;

        PooledObjectInfo pool = ObjectPools.Find(p => p.LookupString == key);

        if (pool == null)
        {
            Debug.LogWarning($"尝试回收到不存在的对象池：{key}");
            return;
        }

        obj.SetActive(false);
        pool.InactiveObjects.Add(obj);
    }
}

/// <summary>
/// 单个对象池的信息结构体
/// </summary>
public class PooledObjectInfo
{
    public string LookupString;                       // 用于查找池的关键字（一般是预制体名字）
    public List<GameObject> InactiveObjects = new();  // 当前未激活的对象列表
    public GameObject container;                      // 用于在层级中整理对象
}
